//
//  KFChoseCell.m
//  KafeeSale
//
//  Created by Liboom on 2025/6/9.
//

#import "KFChoseCell.h"

@interface KFChoseCell() <UITextFieldDelegate>

@end

@implementation KFChoseCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setupUI];
        [self setupConstraints];
    }
    return self;
}

- (void)setupUI {
    self.contentView.backgroundColor = [UIColor whiteColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    // 商品名称标签
    _nameLab = [[UILabel alloc] init];
    _nameLab.font = [UIFont systemFontOfSize:15];
    _nameLab.textColor = [UIColor blackColor];
    _nameLab.text = @"";
    [self.contentView addSubview:_nameLab];
    
    // 豆子标签（新增）
    _beansLab = [[UILabel alloc] init];
    _beansLab.font = [UIFont systemFontOfSize:14];
    _beansLab.textColor = [UIColor colorWithWhite:0.333 alpha:1.0];
    _beansLab.text = @"";
    _beansLab.numberOfLines = 0;
    [self.contentView addSubview:_beansLab];
    
    // 规格做法标签
    _specPracticeLab = [[UILabel alloc] init];
    _specPracticeLab.font = [UIFont systemFontOfSize:14];
    _specPracticeLab.textColor = [UIColor colorWithWhite:0.333 alpha:1.0];
    _specPracticeLab.text = @"";
    _specPracticeLab.numberOfLines = 0;
    [self.contentView addSubview:_specPracticeLab];
    
    // 价格标签
    _priceLab = [[UILabel alloc] init];
    _priceLab.font = [UIFont systemFontOfSize:15];
    _priceLab.textColor = [UIColor blackColor];
    _priceLab.text = @"";
    [self.contentView addSubview:_priceLab];
    
    // 备注标签
    _remarkLab = [[UILabel alloc] init];
    _remarkLab.font = [UIFont systemFontOfSize:14];
    _remarkLab.textColor = [UIColor colorWithWhite:0.333 alpha:1.0];
    _remarkLab.text = @"备注：";
    [self.contentView addSubview:_remarkLab];
    
    // 备注输入框
    _remarkTF = [[UITextField alloc] init];
    _remarkTF.font = [UIFont systemFontOfSize:14];
    _remarkTF.textColor = [UIColor blackColor];
    _remarkTF.delegate = self;
    _remarkTF.placeholder = @"请输入备注";
    [self.contentView addSubview:_remarkTF];
    
    // 数量标签
    _numLab = [[UILabel alloc] init];
    _numLab.font = [UIFont systemFontOfSize:13];
    _numLab.textColor = [UIColor blackColor];
    _numLab.text = @"0";
    _numLab.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:_numLab];
    
    // 减号按钮
    _minusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_minusBtn setImage:[UIImage imageNamed:@"minus"] forState:UIControlStateNormal];
    [_minusBtn addTarget:self action:@selector(minusBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_minusBtn];
    
    // 加号按钮
    _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_addBtn setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    [_addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_addBtn];
}

- (void)setupConstraints {
    // 名称标签
    _nameLab.sd_layout
    .leftSpaceToView(self.contentView, 70)
    .topSpaceToView(self.contentView, 15)
    .heightIs(18);
    [_nameLab setSingleLineAutoResizeWithMaxWidth:200];
    
    // 豆子标签
    _beansLab.sd_layout
    .leftEqualToView(_nameLab)
    .topSpaceToView(_nameLab, 5)
    .rightSpaceToView(self.contentView, 100)
    .autoHeightRatio(0);
    
    // 规格做法标签
    _specPracticeLab.sd_layout
    .leftEqualToView(_nameLab)
    .topSpaceToView(_beansLab, 5)
    .rightSpaceToView(self.contentView, 100)
    .autoHeightRatio(0);
    
    // 价格标签
    _priceLab.sd_layout
    .leftEqualToView(_nameLab)
    .topSpaceToView(_specPracticeLab, 5)
    .heightIs(18);
    [_priceLab setSingleLineAutoResizeWithMaxWidth:200];
    
    // 备注标签
    _remarkLab.sd_layout
    .leftEqualToView(_nameLab)
    .topSpaceToView(_priceLab, 10)
    .heightIs(18);
    [_remarkLab setSingleLineAutoResizeWithMaxWidth:200];
    
    // 备注输入框
    _remarkTF.sd_layout
    .leftSpaceToView(_remarkLab, 5)
    .centerYEqualToView(_remarkLab)
    .rightSpaceToView(self.contentView, 100)
    .heightIs(25);
    
    // 加号按钮
    _addBtn.sd_layout
    .rightSpaceToView(self.contentView, 20)
    .centerYEqualToView(self.contentView)
    .widthIs(30)
    .heightIs(30);
    
    // 数量标签
    _numLab.sd_layout
    .rightSpaceToView(_addBtn, 10)
    .centerYEqualToView(_addBtn)
    .heightIs(20);
    [_numLab setSingleLineAutoResizeWithMaxWidth:50];
    
    // 减号按钮
    _minusBtn.sd_layout
    .rightSpaceToView(_numLab, 10)
    .centerYEqualToView(_numLab)
    .widthIs(30)
    .heightIs(30);
    
    [self setupAutoHeightWithBottomView:_remarkLab bottomMargin:15];
}

#pragma mark - Button Actions

- (void)addBtnClick {
    self.model.choseCount++;
    self.minusBtn.hidden = NO;
    self.numLab.hidden = NO;
    self.numLab.text = [NSString stringWithFormat:@"%ld", self.model.choseCount];
    
    // 使用计算后的价格
    CGFloat currentPrice = [self.model calculateCurrentPrice];
    self.priceLab.text = [NSString stringWithFormat:@"￥%.2lf", currentPrice * self.model.choseCount];
    
    [self updateSpecPracticeDisplay]; // 更新显示
    
    // 通知外部更新总价
    if (self.reloadBlock) {
        self.reloadBlock();
    }
    
    if (self.addBtnClickBlock) {
        self.addBtnClickBlock();
    }
}

- (void)minusBtnClick {
    if (self.model.choseCount > 0) {
        self.model.choseCount--;
        self.numLab.text = [NSString stringWithFormat:@"%ld", self.model.choseCount];
        
        // 使用计算后的价格
        CGFloat currentPrice = [self.model calculateCurrentPrice];
        self.priceLab.text = [NSString stringWithFormat:@"￥%.2lf", currentPrice * self.model.choseCount];
        
        [self updateSpecPracticeDisplay]; // 更新显示
        
        if (self.model.choseCount == 0) {
            self.minusBtn.hidden = YES;
            self.numLab.hidden = YES;
            
            // 数量减到0时，通知外部移除这个商品
            if (self.removeGoodsBlock) {
                self.removeGoodsBlock(self.model);
            }
        }
        
        // 通知外部更新总价
        if (self.reloadBlock) {
            self.reloadBlock();
        }
        
        if (self.minusBtnClickBlock) {
            self.minusBtnClickBlock();
        }
    }
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (self.remarkChangeBlock) {
        self.remarkChangeBlock(textField.text);
    }
}

#pragma mark - Set Model

- (void)setModel:(KFProductModel *)model {
    _model = model;
    self.nameLab.text = model.name;
    self.numLab.text = [NSString stringWithFormat:@"%ld", model.choseCount];
    
    // 使用计算后的价格
    CGFloat currentPrice = [model calculateCurrentPrice];
    self.priceLab.text = [NSString stringWithFormat:@"￥%.2lf", currentPrice * model.choseCount];
    
    self.remarkTF.text = model.localRemark ? model.localRemark : @"";
    
    // 显示豆子
    [self updateBeansDisplay];
    
    // 显示规格和做法
    [self updateSpecPracticeDisplay];
    
    // 更新按钮显示状态
    self.minusBtn.hidden = model.choseCount == 0;
    self.numLab.hidden = model.choseCount == 0;
    
    [self updateLayout];
}

- (void)updateBeansDisplay {
    if (self.model.selectedBeans.count > 0) {
        NSMutableArray *beanDetails = [NSMutableArray array];
        VicSingleObject *single = [VicSingleObject getInstance];
        
        for (NSString *beanEnglishName in self.model.selectedBeans) {
            // 使用单例匹配豆子的中文名称
            NSString *beanChineseName = beanEnglishName; // 默认使用英文名
            
            // 遍历单例中的豆子列表，匹配中文名称
            for (NSDictionary *beanDict in single.beansList) { // 假设单例中有beansList属性
                NSString *englishName = beanDict[@"beanValue"]; // 假设字段名
                NSString *chineseName = beanDict[@"beanName"]; // 假设字段名
                
                if ([englishName isEqualToString:beanEnglishName]) {
                    beanChineseName = chineseName ?: beanEnglishName;
                    break;
                }
            }
            
            [beanDetails addObject:beanChineseName];
        }
        
        if (beanDetails.count > 0) {
            NSString *beansString = [beanDetails componentsJoinedByString:@", "];
            self.beansLab.text = [NSString stringWithFormat:@"豆子：%@", beansString];
            self.beansLab.hidden = NO;
            
            // 调整规格做法标签的位置
            _specPracticeLab.sd_layout.topSpaceToView(_beansLab, 5);
        } else {
            self.beansLab.text = @"";
            self.beansLab.hidden = YES;
            
            // 如果没有豆子，调整规格做法标签的位置
            _specPracticeLab.sd_layout.topSpaceToView(_nameLab, 5);
        }
    } else {
        self.beansLab.text = @"";
        self.beansLab.hidden = YES;
        
        // 如果没有豆子，调整规格做法标签的位置
        _specPracticeLab.sd_layout.topSpaceToView(_nameLab, 5);
    }
}
- (void)updateSpecPracticeDisplay {
    NSMutableArray *specPracticeArray = [NSMutableArray array];
    
    // 添加规格（包含价格）
    if (self.model.selectedSpecs.count > 0) {
        NSMutableArray *specDetails = [NSMutableArray array];
        for (KFDishSpecList *spec in self.model.selectedSpecs) {
            if (spec.specPrice) {
                if ((double)spec.specPrice > 0) {
                    [specDetails addObject:[NSString stringWithFormat:@"%@(➕￥%.0lf)", spec.specName, (double)spec.specPrice]];
                }else{
                    [specDetails addObject:[NSString stringWithFormat:@"%@(➖￥%.0lf)", spec.specName, fabs((double)spec.specPrice)]];
                }
            }else{
                [specDetails addObject:[NSString stringWithFormat:@"%@", spec.specName]];
            }
        }
        NSString *specsString = [specDetails componentsJoinedByString:@","];
        [specPracticeArray addObject:specsString];
    }
    
    // 添加做法（包含价格）
    if (self.model.selectedPractices.count > 0) {
        NSMutableArray *practiceDetails = [NSMutableArray array];
        for (NSDictionary *practice in self.model.selectedPractices) {
            NSString *practiceName = practice[@"cookName"];
            id priceValue = practice[@"cookPrice"];
            
            if (practiceName) {
                // 检查价格是否为0、空或空字符串
                BOOL shouldShowPrice = NO;
                if (priceValue) {
                    if ([priceValue isKindOfClass:[NSNumber class]]) {
                        shouldShowPrice = [priceValue floatValue] > 0;
                    } else if ([priceValue isKindOfClass:[NSString class]]) {
                        NSString *priceStr = (NSString *)priceValue;
                        shouldShowPrice = priceStr.length > 0 && [priceStr floatValue] > 0;
                    }
                }
                
                if (shouldShowPrice) {
                    // 有有效价格时显示价格
                    if ([priceValue doubleValue] > 0) {
                        [practiceDetails addObject:[NSString stringWithFormat:@"%@(➕￥%@)", practiceName, priceValue]];
                    }else{
                        [practiceDetails addObject:[NSString stringWithFormat:@"%@(➖￥%.0lf)", practiceName, fabs([priceValue doubleValue])]];
                    }
                } else {
                    // 价格为0、空或空字符串时只显示名称
                    [practiceDetails addObject:practiceName];
                }
            }
        }
        NSString *practicesString = [practiceDetails componentsJoinedByString:@","];
        [specPracticeArray addObject:practicesString];
    }
    
    if (specPracticeArray.count > 0) {
        NSString *content = [specPracticeArray componentsJoinedByString:@" | "];
        self.specPracticeLab.text = [NSString stringWithFormat:@"规格做法：%@", content];
        self.specPracticeLab.hidden = NO;
        
        // 调整价格标签位置
        _priceLab.sd_layout.topSpaceToView(_specPracticeLab, 5);
    } else {
        self.specPracticeLab.text = @"";
        self.specPracticeLab.hidden = YES;
        
        // 如果没有规格做法，根据是否有豆子调整价格标签位置
        if (self.beansLab.hidden) {
            _priceLab.sd_layout.topSpaceToView(_nameLab, 10);
        } else {
            _priceLab.sd_layout.topSpaceToView(_beansLab, 10);
        }
    }
}
@end
